import React, {useEffect, useState} from 'react';
import { listTree } from '@/services/system/duty';
import { treeDataWrapper } from '@/utils/common';
import { TreeSelect } from 'antd';

const SystemDutyTreeSelect = (props) => {
  const {onChange, value, multiple, placeholder, disabledKey} = props;

  const [treeSelectData, handleTreeSelectData] = useState([]);
  const [dutyValue, handleDutyValue] = useState(undefined);

  useEffect( () => {
    const lostData = async () => {
      const response = await listTree();
      const listData = Array.isArray(response.data) ? response.data : [];

      return listData;
    };

    lostData().then((listData) =>{
      treeDataWrapper(listData, {keyLabel: 'value', disabledKey: disabledKey});
      handleTreeSelectData(listData);
      handleDutyValue(value || undefined);
    });
  }, []);

  const selectItem = (e) => {
    handleDutyValue(e)
    onChange(e)
  }

  return (
    <TreeSelect
      multiple={multiple}
      showSearch
      style={{ width: '100%' }}
      value={dutyValue}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      treeData={treeSelectData}
      onChange={selectItem}
      placeholder={placeholder}
    />
  );
}

export default SystemDutyTreeSelect;